import logging
from sqlalchemy import and_

from rest_api.rest_api_server.controllers.base import BaseController
from rest_api.rest_api_server.controllers.base_async import BaseAsyncControllerWrapper
from rest_api.rest_api_server.controllers.employee import EmployeeController
from rest_api.rest_api_server.controllers.organization import OrganizationController
from rest_api.rest_api_server.models.models import Employee
from rest_api.rest_api_server.models.enums import (
    RolePurposes, InviteAssignmentScopeTypes)

from optscale_client.herald_client.client_v2 import Client as HeraldClient
from currency_symbols.currency_symbols import CURRENCY_SYMBOLS_MAP

LOG = logging.getLogger(__name__)


class RegisterController(BaseController):
    def add_default_owner(self, organization, employee):
        pool = organization.pool
        pool.default_owner_id = employee.id
        self.session.add(pool)
        self.session.commit()

    def add_organization(self, name, user_info, currency=None, is_demo=False):
        currency = currency or 'USD'
        skip_greetings_email = True
        if not is_demo:
            number_of_organizations = self.session.query(Employee).filter(
                and_(
                    Employee.auth_user_id == user_info['id'],
                    Employee.deleted.is_(False)
                )).count()
            skip_greetings_email = number_of_organizations != 0
        org = OrganizationController(
            self.session, self._config, self.token).create(
            name=name, currency=currency, is_demo=is_demo)
        self.assign_role_to_user(user_info['id'], org.id,
                                 RolePurposes.optscale_manager.value,
                                 InviteAssignmentScopeTypes.ORGANIZATION.value)
        employee_ctl = EmployeeController(
            self.session, self._config, self.token
        )
        employee = employee_ctl.create(
            organization_id=org.id,
            name=user_info['display_name'],
            auth_user_id=user_info['id']
        )
        if not is_demo:
            employee_ctl.send_new_employee_email(
                org.id, org.name, org.currency, employee.id, user_info['email'],
                user_info['is_password_autogenerated'])
        if not skip_greetings_email:
            self.send_greetings_email(user_info, org.id, org.name, org.currency)
        self.add_default_owner(org, employee)
        return org, employee

    def register_new_organization(self, **kwargs):
        name = kwargs.get('name')
        currency = kwargs.get('currency')
        user_info = self.get_user_info()
        org, employee = self.add_organization(name, user_info, currency=currency)
        return org

    def send_greetings_email(self, user_info, org_id, org_name, currency):
        template_params = {
            'texts': {
                'name': user_info['display_name'],
                'organization': {
                    'id': org_id,
                    'name': org_name,
                    'currency_code': CURRENCY_SYMBOLS_MAP.get(currency, '$')
                }
            }
        }
        HeraldClient(
            url=self._config.herald_url(),
            secret=self._config.cluster_secret()
        ).email_send(
            [user_info['email']],
            f'Thank you for registering at {self._config.product_name()}. '
            'Please proceed with the setup',
            template_type="employee_greetings", template_params=template_params
        )


class RegisterAsyncController(BaseAsyncControllerWrapper):
    def _get_controller_class(self):
        return RegisterController
